package com.ibiz.znjd.baidu.location;

import static com.baidu.geofence.GeoFenceClient.GEOFENCE_IN_OUT;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.widget.Toast;

import com.baidu.geofence.GeoFence;
import com.baidu.geofence.GeoFenceClient;
import com.baidu.geofence.GeoFenceListener;
import com.baidu.mapapi.model.LatLng;
import com.ibiz.znjd.MainApplication;
import com.ibiz.znjd.znjd.PersonUtil;
import com.ibiz.znjd.znjd.WaringUtil;

import java.util.List;
import java.util.UUID;

public class GeoFenceService {

    // 调用的Context
    private MainApplication app;

    private GeoFenceClient mGeoFenceClient;

    /**
     * 围栏配置对象
     */
    private GeoFenceConfig fenceConfig;

    //定义接收的action字符串
    public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";

    /***
     * 初始化 LocationClient
     *
     * @param _context
     */
    public GeoFenceService(MainApplication _context, GeoFenceConfig fenceConfig) {
        this.app = _context;
        this.fenceConfig = fenceConfig;
        this.initGeoFenceClient();
    }

    public void initGeoFenceClient(){
        mGeoFenceClient = new GeoFenceClient(app);
        // 设置围栏进出时触发监听
        mGeoFenceClient.setActivateAction(GEOFENCE_IN_OUT);
        // 设置即将触发侦听行为时设置定位模式为高精度定位模式
        mGeoFenceClient.isHighAccuracyLoc(true);
//        mGeoFenceClient.setTriggerCount(2,2,2);
        // 业务标识
        String businessId = UUID.randomUUID().toString();

        if(this.fenceConfig.getFenceType() == GeoFenceConfig.FenceType.CIRCLE){
            // 设置圆形范围围栏
            mGeoFenceClient.addGeoFence(fenceConfig.getDPoint(), "bd09ll" , fenceConfig.getAroundRadius()*1000, "BD09LL");
        }else if(this.fenceConfig.getFenceType() == GeoFenceConfig.FenceType.DISTRICT){
            // 设置行政区域围栏
            mGeoFenceClient.addGeoFence(fenceConfig.getAreaName(), businessId);
        }

        //创建回调监听
        GeoFenceListener fenceListenter = new GeoFenceListener() {

            @Override
            public void onGeoFenceCreateFinished(List<GeoFence> list, int i, String s) {
                System.out.println("围栏创建完成");
                if(i == GeoFence.ADDGEOFENCE_SUCCESS){//判断围栏是否创建成功
                    Toast.makeText(app, "添加围栏成功!!", Toast.LENGTH_SHORT).show();
                    //geoFenceList是已经添加的围栏列表，可据此查看创建的围栏
                } else {
                    Toast.makeText(app, "添加围栏失败!!", Toast.LENGTH_SHORT).show();
                }
            }
        };
        mGeoFenceClient.setGeoFenceListener(fenceListenter);//设置回调监听

        //创建并设置PendingIntent
        mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);

        IntentFilter filter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(GEOFENCE_BROADCAST_ACTION);
        app.registerReceiver(mGeoFenceReceiver, filter);
    }

    /**
     * 清除围栏
     */
    public void removeGeoFence(){
        mGeoFenceClient.removeGeoFence();
    }

    private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
                //获取Bundle
                Bundle bundle = intent.getExtras();
                //获取围栏行为：
                int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
                //获取自定义的围栏标识：
                String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
                //获取围栏ID:
                String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
                //获取当前有触发的围栏对象：
                GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);

                StringBuffer sb = new StringBuffer();
                switch (status) {
                    case GeoFence.INIT_STATUS_IN:
                        sb.append("围栏初始状态:在围栏内");
                        break;
                    case GeoFence.INIT_STATUS_OUT:
                        sb.append("围栏初始状态:在围栏外");
                        break;
                    case GeoFence.STATUS_LOCFAIL:
                        sb.append("定位失败,无法判定目标当前位置和围栏之间的状态,请确认是否已允许相关权限");
                        break;
                    case GeoFence.STATUS_IN:
                        sb.append("进入围栏 ");
                        WaringUtil.sendYjWarining(app, fence.getCurrentLocation(), "40");
                        break;
                    case GeoFence.STATUS_OUT:
                        sb.append("离开围栏 ");
                        WaringUtil.sendYjWarining(app, fence.getCurrentLocation(), "10");
                        break;
                    case GeoFence.STATUS_STAYED:
                        sb.append("在围栏内停留超过10分钟 ");
                        break;
                    default:
                        break;
                }
                System.out.println("围栏触发："+sb.toString());
                if(fence.getCurrentLocation() != null){
                    LatLng desLatLng = LocationUtils.converter(fence.getCurrentLocation());
                    System.out.println("围栏触发点坐标："+desLatLng.toString());
                    if(fence.getCenter() != null){
                        double distance = LocationUtils.getDistance(fence.getCurrentLocation().getLongitude(), fence.getCurrentLocation().getLatitude(),fence.getCenter().getLongitude(),fence.getCenter().getLatitude());
                        System.out.println("中心点：latitude:"+fence.getCenter().getLatitude()+",longitude:"+fence.getCenter().getLongitude());
                        System.out.println("围栏半径"+fence.getRadius());
                        System.out.println("围栏触发点距离中心点距离："+distance);
                    }
                }
                Toast.makeText(context, ""+sb.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    };
}
